package com.lidx.back.statistics.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lidx.back.statistics.commons.PageInfo;
import com.lidx.back.statistics.dao.IFeedbackDao;
import com.lidx.back.statistics.entity.FeedBack;
@Repository
public class FeedbackImpl implements IFeedbackDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		if(sessionFactory.getCurrentSession() == null){
			return sessionFactory.openSession();
		}
		return sessionFactory.getCurrentSession();
	}
	
	public void insertFeedback(FeedBack feedBack) throws Exception {
		Session session = sessionFactory.getCurrentSession();
		try{
			session.save(feedBack);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("插入数据失败");
		}
	}

	public List<FeedBack> getFeedBacks() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from FeedBack");
		List list = query.list();
		return list;
	}

	public PageInfo queryFeedbackPage(int pageNo, int pageSize) {
		Query query = getSession().createQuery("from FeedBack");
		final int offset = PageInfo.countOffset(pageSize, pageNo);
		query.setFirstResult(offset);
		query.setMaxResults(pageSize);
		List list = query.list();
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNo(pageNo);
		pageInfo.setPageSize(pageSize);
		pageInfo.setList(list);
		long allRow = queryFeedbackPageCount();
		pageInfo.setAllRow(allRow);
		pageInfo.setTotalPage(PageInfo.countTotalPage(pageSize, allRow));
		return pageInfo;
	}

	public Long queryFeedbackPageCount() {
		Query query = getSession().createQuery("select count(1) from FeedBack");
		return  (Long) query.list().get(0);
	}

}
